<template>
    <base-breadcrumb :breadcrumb="!isAudit">
        <template>
            <a-card class="table-page-search-wrapper">
                <titleName title="基本信息" />
                <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapper-col="{ lg: { span: 16 }, sm: { span: 16 } }">
                    <a-row :gutter="24">
                        <a-col :md="16" :sm="16">
                            <a-form-model-item label="所属单位" prop="project" :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                                :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }">
                                <org-tree-select v-model="form.projectId" disabled isAutoSelectFirst checkStrictly
                                    :is-query-projec-detail="false" @select="selectOrg"></org-tree-select>
                            </a-form-model-item>
                        </a-col>
                        <!-- <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属分公司：" prop="branchComId">
                                <SelectSubCompany
                                    v-model="form.branchComId"
                                    :disabled="type === 'view'"
                                    placeholder="请选择"
                                />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属项目：" prop="project">
                                <SelectProject
                                    v-model="form.project"
                                    :disabled="type === 'view'"
                                    placeholder="请选择"
                                    :form="form"
                                    :is-clear="id == ''"
                                    key-value="branchComId"
                                    label-in-value
                                    @change="handleChange"
                                />
                            </a-form-model-item>
                        </a-col> -->
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="名称:" prop="name">
                                <BaseInput v-model="form.name" placeholder="请输入名称" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="发包人全称:">
                                <BaseInput v-model="form.constructionName" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="编制完成日期:" prop="completionDate">
                                <a-date-picker v-model="form.completionDate" :disabled="type === 'view'"
                                    @change="changecompletionDate" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="结构类型:">
                                <BaseInput v-model="form.structureTypeName" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="建筑面积(㎡):" prop="constructionArea">
                                <BaseInput v-model="form.constructionArea" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="中标通知书日期:" prop="winningBidDate">
                                <a-date-picker v-model="form.winningBidDate" :disabled="type === 'view'"
                                    @change="changewinningBidDate" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="实际开工日期:">
                                <BaseInput v-model="form.contractStartDate" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item :label="squareMeterCostLabel" prop="squareMeterCost">
                                <BaseInputNumber v-model="form.squareMeterCost" :max="99999999999999" :min="0"
                                    placeholder="请输入" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item :label="rebarMeterContentLabel" prop="rebarMeterContent">
                                <BaseInputNumber v-model="form.rebarMeterContent" :max="99999999999999" :min="0"
                                    placeholder="请输入" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item :label="concreteMeterContent" prop="concreteMeterContent">
                                <BaseInputNumber v-model="form.concreteMeterContent" :max="99999999999999" :min="0"
                                    placeholder="请输入" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item :label="templateMeterContent" prop="templateMeterContent">
                                <BaseInputNumber v-model="form.templateMeterContent" :max="99999999999999" :min="0"
                                    placeholder="请输入" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="a:自行完成施工图预算价款(含税)(元):" prop="budgetPrice">
                                <BaseInputNumber v-model="form.budgetPrice" :max="99999999999999" :min="0" placeholder="请输入"
                                    :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="b:业主指定分包价款(含税)(元):" prop="subcontractPrice">
                                <BaseInputNumber v-model="form.subcontractPrice" :max="99999999999999" :min="0"
                                    placeholder="请输入" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="c=a+b施工图预算总额(含税)(元):">
                                <BaseInputNumber :max="99999999999999" :min="0" placeholder="请输入" :precision="2" :value="(form.budgetPrice ? form.budgetPrice : 0) +
                                    (form.subcontractPrice ? form.subcontractPrice : 0)
                                    " disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="填报时间:">
                                <BaseInput v-model="form.createTime" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="填报人:">
                                <BaseInput v-model="form.creatorName" disabled />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" :sm="8">
                            <a-form-model-item label="图纸范围:" prop="undertakeScope">
                                <BaseTextarea v-model="form.undertakeScope" placeholder="请输入"
                                    :auto-size="{ minRows: 3, maxRows: 5 }" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" :sm="8">
                            <a-form-model-item label="编制说明:" prop="prepareNote">
                                <BaseTextarea v-model="form.prepareNote" placeholder="请输入"
                                    :auto-size="{ minRows: 3, maxRows: 5 }" :disabled="type === 'view'" />
                            </a-form-model-item>
                        </a-col>
                        <a-col v-if="type === 'view'" :md="24" :sm="24">
                            <a-form-model-item label="附件：" :label-col="{ lg: { span: 3 }, sm: { span: 5 } }"
                                :wrapper-col="{ lg: { span: 18 }, sm: { span: 17 } }">
                                <file-link :file-list="form.fileInfoVOList" />
                            </a-form-model-item>
                        </a-col>
                        <a-col v-else :md="24" :sm="24">
                            <a-form-model-item label="附件上传">
                                <l-table v-if="isUpdate" :upload-arrys="form.fileInfoVOList" business-code="BM18"
                                    @fileArrysData="fileArrysData" />
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </a-card>
            <a-card>
                <titleName title="其他清单"></titleName>
                <a-button class="mb20" type="primary" @click="handleAdd" :disabled="type === 'view'">添行</a-button>
                <a-table :columns="columns" :data-source="form.totalDrawingExtDTOS" bordered :pagination='isshow'>
                    <span slot="index" slot-scope="text, record, index">
                        {{ index + 1 }}
                    </span>
                    <span slot="ysmc" slot-scope="text, record, index" class="requiredFormItem">
                        <a-input v-model="record.budgetName" type="text" :disabled="type === 'view'" />
                    </span>
                    <span slot="dw" slot-scope="text, record, index">
                        <a-input v-model="record.extContent" type="text" :disabled="type === 'view'" />
                    </span>
                    <span slot="nr" slot-scope="text, record, index" class="requiredFormItem">
                        <a-input v-model="record.unit" type="text" :disabled="type === 'view'" />
                    </span>
                    <span slot="operation" slot-scope="text, record,index">
                        <MoreButton>
                            <a @click="deleteCurrent(record, index)" v-btnPermission="'bm_003_loo_02'"
                                :disabled="type === 'view'">删除</a>

                        </MoreButton>
                    </span>
                </a-table>
            </a-card>
            <div v-if="type != 'view'" class="tool-btns page-btn-right-top">
                <!-- <a-button v-if="form.auditStatus == 'DRAFT'" :loading="loading.DELETE" type="danger" @click="deleteDraft()">
                    删除草稿
                </a-button>
                <a-button v-if="form.auditStatus == 'REJECTED'" type="primary" :loading="loading.REJECTED"
                    @click="submitForm('REJECTED')">
                    保存
                </a-button> -->
                <a-button :loading="loading.DRAFT" type="primary" @click="submitForm('DRAFT')">
                    保存草稿
                </a-button>
                <a-button :loading="loading.SUBMITTED" type="primary" @click="submitForm('SUBMITTED')"> 提交 </a-button>
                <a-button type="primary" @click="closeForm()"> 关闭 </a-button>
            </div>
            <div v-else class="tool-btns page-btn-right-top">
                <BasePrintButton v-if="!isAudit && form.auditStatus == 'PAST'" type="primary" :beforePrintFn="print" />
                <a-button class="ml12" v-if="checkVisibleInDetail" type="primary" @click="closeForm()"> 关闭 </a-button>
            </div>
        </template>
        <!-- <selectApprover :businessId="businessId" :processConfig="setProcessConfig"></selectApprover> -->
    </base-breadcrumb>
</template>

<script>
import { addList, editList, deteleList, findList, print } from '@/api/businessAffairs/lumpSumBudget'
import Vue from 'vue'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import { getProjectInfo } from '@/api/businessAffairs/revenueAndCost'
import { isAttachment, checkVisibleInDetail } from '@/utils/util'
import moment from 'moment'
const columns = [
    {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        scopedSlots: { customRender: 'index' },
    },
    {
        title: '预算名称',
        dataIndex: 'ysmc',
        scopedSlots: { customRender: 'ysmc' },
    },
    {
        title: '单位',
        dataIndex: 'dw',
        scopedSlots: { customRender: 'dw' },
    },
    {
        title: '内容',
        dataIndex: 'nr',
        scopedSlots: { customRender: 'nr' },
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: '170px',
        scopedSlots: { customRender: 'operation' },
    },
]
export default {

    name: 'a' + Date.now(),

    components: {
        SelectSubCompany,
        SelectProject
    },
    data() {
        this.columns = columns
        return {
            isshow: false,

            checkVisibleInDetail: checkVisibleInDetail(this),
            rules: {
                name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
                branchComId: [{ required: true, message: '请选择分公司', trigger: 'blur' }],
                project: [{ required: true, message: '请选择项目', trigger: 'blur' }],
                completionDate: [{ required: true, message: '请选择编制完成日期', trigger: 'change' }],
                winningBidDate: [{ required: true, message: '请选择中标通知书日期', trigger: 'change' }],
                squareMeterCost: [{ required: true, message: '请输入平米造价(元/㎡)(自行完成)', trigger: 'change' }],
                rebarMeterContent: [{ required: true, message: '请输入钢筋公里含量(kg/㎡)', trigger: 'change' }],
                concreteMeterContent: [{ required: true, message: '请输入砼公里含量(m³/㎡)', trigger: 'change' }],
                templateMeterContent: [{ required: true, message: '请输入模板平米含量(㎡/㎡)', trigger: 'change' }],
                budgetPrice: [{ required: true, message: '请输入自行完成施工图预算价款(元)', trigger: 'change' }],
                subcontractPrice: [{ required: true, message: '请输入业主指定分包价款(元)', trigger: 'change' }],
                totalBudget: [{ required: true, message: '请输入施工图预算总额(元)', trigger: 'change' }],
                undertakeScope: [{ required: true, message: '请输入图纸范围', trigger: 'change' }],
                prepareNote: [{ required: true, message: '请输入编制说明', trigger: 'change' }],
                constructionArea: [{ required: true, message: '请输入编制说明', trigger: 'change' }]
            },
            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            form: {
                name: '',
                projectId: '',
                constructionName: '',
                structureTypeName: '',
                constructionArea: '',
                contractStartDate: '',
                rebarMeterContent: 0,
                concreteMeterContent: 0,
                templateMeterContent: 0,
                totalDrawingExtDTOS: [
                    {
                        budgetName: '',
                        extContent: '',
                        unit: '',
                    }
                ],
            },
            type: '',
            hideRequiredMark: false,
            disabled: false,
            isUpdate: true,
            token: '',

            squareMeterCostLabel: '平米造价(含税)(元/㎡)(自行完成)',
            rebarMeterContentLabel: '钢筋公里含量(kg/㎡)',
            concreteMeterContent: '砼公里含量(m³/㎡)',
            templateMeterContent: '模板平米含量(㎡/㎡)',
            //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        isAudit: {
            // 是否作为审批详情
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.type = 'view'
                    })
                }
            }
        }
    },
    async created() {
        this.token = Vue.getAcloudProvider().getAccessToken()
        this.type = this.$route.query.type || ''

        this.id = this.$route.query.id || ''
        this.$route.meta.title = this.id == '' ? '总包施工图预算新增' : '总包施工图预算编辑'
        if (this.type == 'view') {
            this.$route.meta.title = '总包施工图预算查看'
        }
        this.getDetails()
        //获取通过获取流程配置值
        // this.processConfig = await this.$getConfigFn('comm_construction_plan_budget')
    },
    methods: {
        // 添加
        handleAdd() {
            this.form.totalDrawingExtDTOS.push({
                budgetName: '',
                extContent: '',
                unit: '',
            })
        },
        // 删除
        deleteCurrent(record, index) {
            this.form.totalDrawingExtDTOS.splice(index, 1)
        },
        //选择单位
        selectOrg(val) {
            if (val && val.length) {
                this.form.branchComId = val[val.length - 2].orgId;
                this.form.project = { key: val[val.length - 1].projectId, lable: val[val.length - 1].projectName };
                this.handleChange(this.form.project)
            }
        },
        print() {
            return print({ id: this.id }).then((res) => {
                console.log(res)
                return res.data.content
            })
        },
        //获取项目详情
        handleChange(e) {
            this.$nextTick(() => {
                this.form.name = (this.form.project.label || '') + '总包施工图预算'
                console.log(e)
                this.getProjectInfo(e.key)
            })
        },
        getProjectInfo(id) {
            if (!id) return
            let params = {
                projectId: id
            }

            getProjectInfo(params).then((res) => {
                if (this.type == '') {
                    this.$set(this.form, 'constructionArea', (res.data.contractTotalArea * 10000).toFixed(0))
                }

                this.$set(this.form, 'constructionName', res.data.constructionName)
                this.$set(this.form, 'structureTypeName', res.data.structureTypeName)
                this.$set(this.form, 'contractStartDate', res.data.contractStartDate)
                if (res.data.projectTypeName == '线性基础设施') {
                    this.squareMeterCostLabel = '公里造价(元/km)(自行完成)'
                    this.rebarMeterContentLabel = '钢筋公里含量(kg/km)'
                    this.concreteMeterContent = '砼公里含量(m³/km)'
                    this.templateMeterContent = '模板公里含量(㎡/km)'
                } else {
                    this.squareMeterCostLabel = '平米造价(含税)(元/㎡)(自行完成)'
                    this.rebarMeterContentLabel = '钢筋平米含量(kg/㎡)'
                    this.concreteMeterContent = '砼平米含量量(m³/㎡)'
                    this.templateMeterContent = '模板平米含量(㎡/㎡)'
                }
                console.log(this.form)
            })
        },
        getDetails() {
            if (this.id) {
                this.isUpdate = false
                let params = { id: this.id }
                findList(params).then((res) => {
                    this.isUpdate = true
                    this.form = { ...res.data, project: { key: res.data.projectId, lable: res.data.projectName } }
                    if (res.data.totalDrawingExtDTOS == null || res.data.totalDrawingExtDTOS == '') {
                        this.form.totalDrawingExtDTOS = [
                            {
                                budgetName: '',
                                extContent: '',
                                unit: '',
                            }
                        ]
                    }
                    console.log(res, 'resssssssssssss')
                    if (this.type !== 'view') {
                        this.form.creatorName = this.$userInfo().name
                        this.form.createTime = moment().format('YYYY-MM-DD')
                    }

                    this.getProjectInfo(this.form.projectId)
                })
            }
        },
        fileArrysData(val) {
            this.form.fileInfoVOList = val
        },
        changewinningBidDate(value, dateString) {
            this.form.winningBidDate = dateString
        },
        changecompletionDate(value, dateString) {
            this.form.completionDate = dateString
        },
        // 删除草稿
        deleteDraft() {
            let that = this
            this.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return deteleList({ id: that.id })
                        .then((res) => {
                            that.$message.success('删除成功！')
                            that.closeForm()
                        })
                        .catch((res) => {
                            that.$message.warning('删除失败！')
                        })
                },
                onCancel() {
                    // console.log('Cancel')
                }
            })
        },

        submitForm(auditStatus) {
            let statusCurrent = true;
            this.setProcessConfig = null;
            this.form.totalDrawingExtDTOS.forEach((item, index) => {
                for (let key in item) {
                    if (key == 'budgetName' || key == 'unit') {
                        if (item[key] === '' || item[key] === null) {

                            statusCurrent = false
                            break
                        }
                    }
                }
            })
            if (!statusCurrent) {
                this.$message.warning("请填写完所有必填项信息")
                return
            }


            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
                    const params = this.$clone(this.form)
                    params.projectId = params.project.key
                    delete params.project
                    this.loading[auditStatus] = true
                    params.auditStatus = auditStatus
                    params.totalBudget = params.budgetPrice + params.subcontractPrice
                    this.submitApprovalConfirm(6, (flag) => {
                        if (!flag) {
                            this.loading[auditStatus] = false
                            return
                        }
                        if (this.$route.query.id) {
                            // let obj = {
                            //     ...params,
                            //     id: this.$route.query.id,
                            //     auditStatus: auditStatus == 'DRAFT' ? 0 : 1,
                            // }
                            editList(params).then((res) => {
                                this.$refs.ruleForm.resetFields()
                                this.loading[auditStatus] = false
                                if (res.code === 200) {
                                    this.$message.success('成功')

                                    this.closeForm()

                                } else {
                                    this.$message.error('编辑失败')
                                }
                            }).catch(()=>{
                                this.loading[auditStatus] = false
                            })
                        } else {
                            addList(params).then((res) => {
                                this.loading[auditStatus] = false
                                this.$refs.ruleForm.resetFields()
                                if (res.code === 200) {
                                    this.$message.success('成功')
                                    // if (auditStatus == 'SUBMITTED') {
                                    //     //提交时，返回id
                                    //     this.businessId = res.data.id || this.$route.query.id;
                                    //     this.setProcessConfig = this.processConfig;
                                    //     return
                                    // } else {
                                    this.closeForm()
                                    // this.$route.push()
                                    // }
                                } else {
                                    this.$message.error('新增失败')
                                }
                            }).catch(()=>{
                                this.loading[auditStatus] = false
                            })
                        }
                    })
                } else {
                    this.$message.warning("请填写完所有必填项信息")
                }
            })

        },
        closeForm() {
            if (this.isAudit) {
                window.close()
            } else {
                this.$multiTab.close(this.$route.fullpath)
            }
        }
    }
}
</script>

<style lang="less" scoped>
@deep: ~'>>>';

.tool-btns {
    display: flex;
    justify-content: flex-end;

    @{deep} .ant-btn+.ant-btn {
        margin-left: 12px;
    }
}

.foot-btn {
    display: flex;
    justify-content: space-between;
}

.ant-calendar-picker {
    width: 100%;
}

.table-page-search-wrapper {
    @{deep} .ant-col-md-8 {
        height: 65px;
    }
}
</style>
